package com.ohuang.demo.webView

import android.content.Context
import android.os.Build
import android.util.Log
import android.webkit.CookieManager
import android.webkit.CookieSyncManager
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.ui.res.integerResource
import com.ohuang.demo.storage.getSpStorage
import com.ohuang.demo.storage.setValue
import com.ohuang.demo.storage.getValue


class SteamWebView {
    private val TAG = "SteamWebView"

    var cdk = ""

    private var steamUrl = "https://store.steampowered.com"
    private var loginSteamUrl = "https://login.steampowered.com"

    private var mWebView: WebView? = null

    private var js: String = """
        window.gsApp_steamGameKey = "#SteamCDKey#";
        window.gsApp_steamUserId = "#用户SteamID#";
     

        console.log(new Date() + "，Steam绑定程序脚本文件，加载成功。");
        window.gsApp_jiHuoCDKeyButtonClickred = 'none'


            


        function postMessageToApp (msg)
        {
        	var aTag = document.createElement("A");
        	{
        		aTag.setAttribute("href", "fhyx://" + msg);
        		aTag.setAttribute("target", "_self");
        		document.body.insertAdjacentElement("beforeend", aTag);
        	}
        	aTag.click();
        }
        function postMsg_PageLoadCompleted ()
        {
        	recordEvent_PageLoadSuccess();
        	recordEvent_LoginButtonShow();
        	// 1/2，通知App，页面加载成功：
        	postMessageToApp("steam.loginPage.didLoadCompleted");
        }
        function postMsg_LoginButtonClicked ()
        {
        	recordEvent_LoginButtonClick();
        	postMessageToApp("steam.loginPage.didLoginButtonClicked");
        }
        function postMsg_LoginSecondAuthShow ()
        {
        	recordEvent_SecondAuthShow();
        	postMessageToApp("steam.loginPage.didLoginSecondAuthShow");
        }
        function postMsg_AgreeAuthLogin ()
        {
        	recordEvent_AgreeAuthLogin();
        	postMessageToApp("steam.loginPage.didAgreeAuthLogin");
        }
        function postMsg_LoginFormSubmit ()
        {
        	postMessageToApp("steam.loginPage.didLoginFormSubmit");
        }
        function postMsg_AddToWishListCompleted ()
        {
        	postMessageToApp("steam.wishList.addToWishListCompleted");
        }

        function httpGet (url)
        {
        	try
        	{
        		// var xmlhttp = new XMLHttpRequest();
        		// xmlhttp.onreadystatechange = function ()
        		// {
        		// 	if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        		// 	{ }
        		// }
        		// xmlhttp.open("GET", url, true);
        		// xmlhttp.send();
        		var imgNode = document.createElement("img");
        		{
        			imgNode.style = "display: none;"
        			imgNode.setAttribute("src", url);
        		}
        		document.body.appendChild(imgNode);
        	}
        	catch (exception)
        	{
        		console.error(exception);
        	}
        }
        function recordEvent (eventTypeId, errorInfo = null)
        {
        	
        }

        if (window.gsApp_isRecored_LoadPage == undefined)
        {
        	window.gsApp_isRecored_LoadPage = false;
        }
        function recordEvent_LoadPage ()
        {
        	if (window.gsApp_isRecored_LoadPage == false)
        	{
        		window.gsApp_isRecored_LoadPage = true;
        		recordEvent(1);
        	}
        }

        if (window.gsApp_isRecored_PageLoadSuccess == undefined)
        {
        	window.gsApp_isRecored_PageLoadSuccess = false;
        }
        function recordEvent_PageLoadSuccess ()
        {
        	if (window.gsApp_isRecored_PageLoadSuccess == false)
        	{
        		window.gsApp_isRecored_PageLoadSuccess = true;
        		recordEvent(2);
        	}
        }

        if (window.gsApp_isRecored_LoginButtonShow == undefined)
        {
        	window.gsApp_isRecored_LoginButtonShow = false;
        }
        function recordEvent_LoginButtonShow ()
        {
        	if (window.gsApp_isRecored_LoginButtonShow == false)
        	{
        		window.gsApp_isRecored_LoginButtonShow = true;
        		recordEvent(11);
        	}
        }

        if (window.gsApp_isRecored_LoginButtonClick == undefined)
        {
        	window.gsApp_isRecored_LoginButtonClick = false;
        }
        function recordEvent_LoginButtonClick ()
        {
        	if (window.gsApp_isRecored_LoginButtonClick == false)
        	{
        		window.gsApp_isRecored_LoginButtonClick = true;
        		recordEvent(12);
        	}
        }

        if (window.gsApp_isRecored_SecondAuthShow == undefined)
        {
        	window.gsApp_isRecored_SecondAuthShow = false;
        }
        function recordEvent_SecondAuthShow ()
        {
        	if (window.gsApp_isRecored_SecondAuthShow == false)
        	{
        		window.gsApp_isRecored_SecondAuthShow = true;
        		recordEvent(4.2);
        	}
        }

        if (window.gsApp_isRecored_AgreeAuthLogin == undefined)
        {
        	window.gsApp_isRecored_AgreeAuthLogin = false;
        }
        function recordEvent_AgreeAuthLogin ()
        {
        	if (window.gsApp_isRecored_AgreeAuthLogin == false)
        	{
        		window.gsApp_isRecored_AgreeAuthLogin = true;
        		recordEvent(4.1);
        	}
        }

        if (window.gsApp_isRecored_E84 == undefined)
        {
        	window.gsApp_isRecored_E84 = false;
        }
        function recordEvent_E84 ()
        {
        	if (window.gsApp_isRecored_E84 == false)
        	{
        		window.gsApp_isRecored_E84 = true;
        		recordEvent(-84);
        	}
        }

        if (window.gsApp_isRecored_OtherError == undefined)
        {
        	window.gsApp_isRecored_OtherError = false;
        }
        function recordEvent_OtherError (errorInfo)
        {
        	if (window.gsApp_isRecored_OtherError == false)
        	{
        		window.gsApp_isRecored_OtherError = true;
        		recordEvent(-1, errorInfo);
        	}
        }
        console.log(new Date() + "，检查登录UI，准备开始。");

        if (window.gsApp_steamLoginButtonLastCheckTime != undefined
        	&& (new Date().getTime() - window.gsApp_steamLoginButtonLastCheckTime) < 1000)
        {
        	console.log(new Date() + "，检查登录UI，之前已开始，本次取消。");
        }
        else
        {
        	console.log(new Date() + "，检查登录UI，已开始。");

        	window.gsApp_loginFormNeedTargetBlank = true;
        	window.gsApp_steamLoginButtonLastCheckTime = new Date().getTime();
        	window.gsApp_steamLoginButton = null;
        	window.gsApp_LastOpenIdLogout = null;
        	window.gsApp_SecondAuthLogin = null;
        	window.gsApp_AgreeAuthLogin = null;
        	window.gsApp_jiHuoCDKeyCompleted = null;
        	window.gsApp_LastOpenIdLogout_LastInvokeTime = 0;

        	setTimeout(function ()
        	{
        		// !!! 异步执行，避免阻塞 !!!
        		recordEvent_LoadPage();
        		// !!!
        	},
        		100);
        	var jiHuoCDKey = setInterval(function ()
        	{
        		//
        		console.log(new Date() + "，“登录按钮”轮询检查，准备开始。");
        		//

        		window.gsApp_steamLoginButtonLastCheckTime = new Date().getTime();

        		if (window.gsApp_loginFormNeedTargetBlank)
        		{
        			var loginForm = document.getElementById("openidForm");
        			if (loginForm != null)
        			{
        				loginForm.setAttribute("target", "_blank");
        			}
        		}

        		////////////////////////////////////////////////
        		// 1/2，账号密码登录页面：
        		////////////////////////////////////////////////
        		//
        		console.log(new Date() + "，“登录按钮”轮询检查，开始。");
        		//
        		if (window.gsApp_steamLoginButton == null)
        		{
        			var steamLoginButton = null;
        			var buttons = document.querySelectorAll("button");
        			for (var button of buttons)
        			{
        				if (button.innerHTML.indexOf("登录") >= 0)
        				{
        					steamLoginButton = button;
        					break;
        				}
        			}
        			if (steamLoginButton == null)
        			{
        				buttons = document.querySelectorAll("input");
        				for (var button of buttons)
        				{
        					if (button.innerText.indexOf("登录") >= 0)
        					{
        						steamLoginButton = button;
        						break;
        					}
        				}
        			}
        			window.gsApp_steamLoginButton = steamLoginButton;
        				
        			if (window.gsApp_steamLoginButton != null)
        			{	
        				//
        				console.log(new Date() + "，“登录按钮”轮询检查，发现登录按钮。");
        				//

        				////////////////////////////////////////////////
        				// 1/2，增加点击事件：
        				////////////////////////////////////////////////
        				steamLoginButton.addEventListener(
        					"click",
        					function ()
        					{
        						// !!!
        						postMsg_LoginButtonClicked();
        						// !!!
        					});
        				// 获取“steamLoginButton”所属的form表单：
        				var steamLoginForm = steamLoginButton.form;
        				if (steamLoginForm)
        				{
        					steamLoginForm.addEventListener(
        						"submit",
        						(event) =>
        						{
        							// !!!
        							postMsg_LoginFormSubmit();
        							// !!!
        						});
        				}

        				////////////////////////////////////////////////
        				// 2/2，展示页面UI：
        				////////////////////////////////////////////////
        				// !!!
        				postMsg_PageLoadCompleted();
        				// !!!
        			}
        			else
        			{
        				//
        				console.log(new Date() + "，“登录按钮”轮询检查，没有发现登录按钮。");
        				//
        			}
        		}
        		else
        		{
        			//
        			console.log(new Date() + "，“登录按钮”轮询检查，登录按钮，已完成检查。");
        			//
        		}

        		////////////////////////////////////////////////
        		// 2/2，Cookie授权页面：
        		////////////////////////////////////////////////
        		if (window.gsApp_steamLoginButton == null)
        		{
        			steamLoginButton = null;
        			buttons = document.querySelectorAll("input");
        			for (var button of buttons)
        			{
        				if (button.value
        					&& button.value.indexOf("登录") >= 0)
        				{
        					steamLoginButton = button;
        					break;
        				}
        			}
        			if (steamLoginButton == null)
        			{
        				buttons = document.querySelectorAll("button");
        				for (var button of buttons)
        				{
        					if (button.innerText.indexOf("登录") >= 0)
        					{
        						steamLoginButton = button;
        						break;
        					}
        				}
        			}

        			window.gsApp_steamLoginButton = steamLoginButton;
        			if (window.gsApp_steamLoginButton != null)
        			{
        				////////////////////////////////////////////////
        				// 1/2，增加点击事件：
        				////////////////////////////////////////////////
        				steamLoginButton.addEventListener(
        					"click",
        					function ()
        					{
        						// !!!
        						postMsg_LoginButtonClicked();
        						// !!!
        					});
        				// 获取“steamLoginButton”所属的form表单：
        				var steamLoginForm = steamLoginButton.form;
        				if (steamLoginForm)
        				{
        					steamLoginForm.addEventListener(
        						"submit",
        						(event) =>
        						{
        							// !!!
        							postMsg_LoginFormSubmit();
        							// !!!
        						});
        				}

        				////////////////////////////////////////////////
        				// 2/2，展示页面UI：
        				////////////////////////////////////////////////
        				// !!!
        				postMsg_PageLoadCompleted();
        				// !!!
        			}

        			// “这不是您”的处理：
        			if (window.gsApp_LastOpenIdLogout == null)
        			{
        				window.gsApp_LastOpenIdLogout = window.OpenIdLogout;
        				window.OpenIdLogout = function ()
        				{
        					var now = new Date().getTime();
        					// 3 秒内不重复调用：
        					if (now - window.gsApp_LastOpenIdLogout_LastInvokeTime < 3000)
        					{
        						return;
        					}
        					// !!!
        					window.gsApp_LastOpenIdLogout_LastInvokeTime = now;
        					window.gsApp_LastOpenIdLogout();
        					// !!!
        				};
        			}
        		}

        		////////////////////////////////////////////////
        		// 3/，检查上报错误信息：
        		////////////////////////////////////////////////
        		if (window.gsApp_isRecored_E84 == false)
        		{
        			var isE84 = document.body.innerText.indexOf("e84") >= 0;
        			if (isE84)
        			{
        				recordEvent_E84();
        			}
        		}
        		if (window.gsApp_isRecored_E84 == false
        			&& window.gsApp_isRecored_OtherError == false)
        		{
        			var bodyInnerText = document.body.innerText;
        			var errorInfoBeginIndex = bodyInnerText.indexOf("错误代码");
        			if (errorInfoBeginIndex >= 0)
        			{
        				var errorInfoLength = 10;
        				if (errorInfoBeginIndex + errorInfoLength > bodyInnerText.length)
        				{
        					errorInfoLength = bodyInnerText.length - errorInfoBeginIndex;
        				}
        				var errorInfo = null;
        				if (errorInfoLength > 0)
        				{
        					errorInfo = bodyInnerText.substring(
        						errorInfoBeginIndex,
        						errorInfoBeginIndex + errorInfoLength);
        				}
        				recordEvent_OtherError(errorInfo);
        			}
        		}

        		////////////////////////////////////////////////
        		// 4/，二次验证页面：
        		////////////////////////////////////////////////
        		if (window.window.gsApp_SecondAuthLogin == null)
        		{
        			var secondAuthDiv = document.querySelectorAll('div');
        			secondAuthDiv.forEach(item =>
        			{
        				if (item.innerHTML.includes('此帐户受到手机验证器保护'))
        				{
        					window.window.gsApp_SecondAuthLogin = item;
        					postMsg_LoginSecondAuthShow();
        				}
        			})
        		}

        		////////////////////////////////////////////////
        		// 5/，授权登录页面：
        		////////////////////////////////////////////////
        		if (window.gsApp_AgreeAuthLogin == null)
        		{
        			var agreeAuthLogin = document.getElementById("imageLogin");
        			if (agreeAuthLogin != null)
        			{
        				window.window.gsApp_SecondAuthLogin = agreeAuthLogin;
        				agreeAuthLogin.addEventListener(
        					"click",
        					function ()
        					{
        						// !!!
        						postMsg_AgreeAuthLogin();
        						// !!!
        					});
        			}
        		}

        		////////////////////////////////////////////////
        		// 6/激活CDKEY：
        		////////////////////////////////////////////////
        		if (window.location.href.indexOf("?redir=") == -1 && window.gsApp_jiHuoCDKeyCompleted == null
        		&& window.location.href.indexOf("https://store.steampowered.com/") >= 0 && window.location.href.indexOf("/registerkey") >= 0){

        			

        			var userInfoElement = document.getElementById("application_config").getAttribute("data-userinfo");
        			var userInfo = JSON.parse(userInfoElement);
        			var steamid = userInfo.steamid;
        			console.log("steamid="+steamid);

        			// if (steamid != window.gsApp_steamUserId && window.gsApp_steamUserId != '#用户SteamID#'){
        			// 	window.clearInterval(jiHuoCDKey);
        			// 	postMsg_PageLoadCompleted();
        			// 	window.location.href = "https://www.baidu.com/s?wd=444&steamid="+steamid;
        			// }

        			document.getElementById("product_key").value = window.gsApp_steamGameKey;
        			document.getElementById("accept_ssa").checked = true;
        			if (window.gsApp_jiHuoCDKeyButtonClickred == "completed"){
        				window.gsApp_jiHuoCDKeyCompleted = true
        				window.clearInterval(jiHuoCDKey);
        				var receipt_form = document.getElementById("receipt_form")
        				var error_display = document.getElementById("error_display")
        				var checkJiHuo = setInterval(() => {
        					if(!error_display.offsetParent && receipt_form.offsetParent && window.gsApp_jiHuoCDKeyCompleted){
        						// 激活成功
        						window.gsApp_jiHuoCDKeyCompleted = 'completed'
        						window.clearInterval(checkJiHuo);
        						setTimeout(() => {
        					
        							setTimeout(() => {
        								postMsg_PageLoadCompleted();
        								window.location.href = "https://www.baidu.com/s?wd=222&steamid="+steamid
        							}, 1000);
        						}, 1000);
        					}else if(error_display.offsetParent && !receipt_form.offsetParent && window.gsApp_jiHuoCDKeyCompleted){
        						window.gsApp_jiHuoCDKeyCompleted = 'completed'
        						window.clearInterval(checkJiHuo);
        						postMsg_PageLoadCompleted();
        						window.location.href = "https://www.baidu.com/s?wd=111&steamid="+steamid;

        					}
        				}, 300);
        			}
        			if(document.getElementById("accept_ssa").checked == true && window.gsApp_jiHuoCDKeyButtonClickred == 'none'){
        				document.getElementById("register_btn").click();
        				window.gsApp_jiHuoCDKeyButtonClickred = "completed";
        			}
        		}
        	},
        		300);
        }
    """.trimIndent()

    private var mWebViewClient = object : WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {


            return super.shouldOverrideUrlLoading(view, url)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            Log.d(TAG, "onPageFinished: url=$url")
            if (url == "https://store.steampowered.com/account/registerkey") {
                mWebView?.postDelayed({
                    registerKey()
                    mWebView?.context?.apply {
                        saveCookie(this)
                    }

                }, 1000)

            }
        }
    }

    private var mWebChromeClient = object : WebChromeClient() {


    }

    private fun saveCookie(context: Context) {
        val cookie = CookieManager.getInstance().getCookie(steamUrl)
        val cookieLogin = CookieManager.getInstance().getCookie(loginSteamUrl)
        var steamCookie: String by context.getSpStorage(TAG, "")
        var steamLoginCookie: String by context.getSpStorage(TAG, "")
        steamCookie = cookie
        steamLoginCookie = cookieLogin
    }

    private fun getSteamCookie(context: Context): String {
        var steamCookie: String by context.getSpStorage(TAG, "")
        return steamCookie
    }

    private fun getSteamLoginCookie(context: Context): String {
        var steamLoginCookie: String by context.getSpStorage(TAG, "")
        return steamLoginCookie
    }


    fun initWebView(webView: WebView) {
        mWebView = webView
        val cookieManager = CookieManager.getInstance()
        var cookie = getSteamCookie(webView.context)
        if (cookie.isNotEmpty()) {
//            removeCookie(cookieManager, webView, webView.context, steamUrl)
            setCookie(cookieManager, webView, webView.context, steamUrl, cookie)
        }
        var cookieLogin = getSteamLoginCookie(webView.context)
        if (cookieLogin.isNotEmpty()) {
            setCookie(cookieManager, webView, webView.context, loginSteamUrl, cookieLogin)
        }
        WebView.setWebContentsDebuggingEnabled(true)
        webView.defaultSetting()

        webView.webViewClient = mWebViewClient
        webView.webChromeClient = mWebChromeClient
    }

    private fun setCookie(
        cookieManager: CookieManager,
        webView: WebView,
        context: Context,
        url: String,
        cookies: String
    ) {
        cookieManager.setAcceptCookie(true) // 确保 Cookie 功能开启
        cookieManager.setAcceptThirdPartyCookies(webView, true);
        if (!cookies.isNullOrEmpty()) {
            // 分割每个 Cookie
            cookies.split(";").forEach { cookie ->
                // 设置过期时间为过去时间以删除 Cookie
                cookieManager.setCookie(url, cookie, {
                    Log.d(TAG, "setCookie: $cookie " + it)
                })
            }

        }

        Log.d(TAG, "setCookie: cookie=" + cookieManager.getCookie(url))
        // 同步 Cookie 更改
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.flush()
        } else {
            @Suppress("DEPRECATION")
            CookieSyncManager.createInstance(context).sync()
        }
    }


    private fun removeCookie(
        cookieManager: CookieManager,
        webView: WebView,
        context: Context,
        url: String
    ) {
        cookieManager.setAcceptCookie(true) // 确保 Cookie 功能开启
        cookieManager.setAcceptThirdPartyCookies(webView, true);
//        cookieManager.removeAllCookies({})
        var cookies = cookieManager.getCookie(url)
        if (!cookies.isNullOrEmpty()) {
            cookies.split(";").forEach { cookie ->
                // 设置过期时间为过去时间以删除 Cookie
                val cookieName = cookie.split("=").first().trim()
                cookieManager.setCookie(url, "$cookieName=", {
                    Log.d(TAG, "removeCookie: $cookieName " + it)
                })
            }
        }
        Log.d(TAG, "removeCookie: getCookie=" + cookieManager.getCookie(url))
        // 同步 Cookie 更改
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.flush()
        } else {
            @Suppress("DEPRECATION")
            CookieSyncManager.createInstance(context).sync()
        }
    }


    fun startRegisterKey(cdk: String) {
        this.cdk = cdk
        mWebView?.apply {
            loadUrl("https://store.steampowered.com/login?redir=account/registerkey")
            registerKey()
        }
    }

    private fun registerKey() {
        mWebView?.evaluateJavascript(js.replaceFirst("#SteamCDKey#", cdk)) {
            Log.d(TAG, "startCdk: $it")
        }
    }

    fun onDestroy() {

        mWebView = null
    }

}